package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.nursing.domain.dto.DeviceDataPageQueryDto;
import com.zzyl.nursing.domain.pojo.Device;
import com.zzyl.nursing.domain.pojo.DeviceData;
import com.zzyl.nursing.job.IotMsgHeader;
import com.zzyl.nursing.job.IotMsgNotifyData;
import com.zzyl.nursing.job.IotMsgService;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.service.IDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 设备数据Service业务层处理
 *
 * @author alexis
 * @date 2025-05-30
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 接收设备端数据
     */
    @Override
    public void batchSaveDeviceData(IotMsgNotifyData notifyData) {
        //1.判断设备是否存在(从AmqpClient中的notifyDate对象开始获取,整个contentStr是测试时打印在控制台的Content字符串)
        IotMsgHeader header = notifyData.getHeader();
        String deviceId = header.getDeviceId();
        Device device = deviceService.lambdaQuery()
                .eq(Device::getIotId, deviceId)
                .one();
        if (ObjectUtil.isNull(device)) {
            return;
        }
        List<IotMsgService> services = notifyData.getBody().getServices();
        if (CollectionUtil.isEmpty(services)) {
            return;
        }

        //2.properties数据进行循环构建DeviceData然后做批量保存
        services.forEach(service -> {
            //解析上报时间
            LocalDateTime parseLocalDateTime = LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime alarmTime = parseLocalDateTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            //获取properties的Map集合并遍历,拿其中的key填充值数据库指定字段
            Map<String, Object> properties = service.getProperties();
            //创建一个新集合接收遍历循环的deviceDate
            ArrayList<DeviceData> deviceDataList = new ArrayList<>();
            properties.forEach((key, value) -> {
                //复制属性是会把相同字段进行复制,因此id也会同样复制过去,为了避免这种情况,在BeanUtil工具类中自带了忽略字段的功能
                DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class, CopyOptions.create().setIgnoreProperties("id"));
                //填充唯一一个不同字段名的属性
                deviceData.setAccessLocation(device.getBindingLocation());
                //拿其中的key填充值数据库指定字段
                deviceData.setFunctionId(key);
                deviceData.setDataValue(value.toString());
                deviceData.setAlarmTime(alarmTime);
                //将填充完字段的deviceDate对象放在创建的新集合中
                deviceDataList.add(deviceData);
            });
            saveBatch(deviceDataList);
            //将设备最新数据存入redis缓存中
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA, deviceId, JSONUtil.toJsonStr(deviceDataList));
        });

    }

    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return deviceDataMapper.selectById(id);
    }


    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     *
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return deviceDataMapper.deleteById(id);
    }


    /**
     * 查询设备数据列表
     *
     * @param deviceDataPageReqDto
     * @return 设备数据集合
     */
    @Override
    public TableDataInfo<DeviceData> selectDeviceDataList(DeviceDataPageQueryDto deviceDataPageReqDto) {
        //1.条件查询分页数据
        String functionId = deviceDataPageReqDto.getFunctionId();
        String deviceName = deviceDataPageReqDto.getDeviceName();
        if (StrUtil.isBlank(functionId) || StrUtil.isBlank(deviceName)) {
            throw new ServiceException("请求的functionId与deviceName不能为空");
        }
        LocalDateTime startTime = deviceDataPageReqDto.getStartTime();
        LocalDateTime endTime = deviceDataPageReqDto.getEndTime();
        if (ObjectUtil.isNull(startTime) || ObjectUtil.isNull(endTime)) {
            throw new ServiceException("时间范围不能为空");
        }
        Page<DeviceData> page = this.lambdaQuery()
                .eq(DeviceData::getFunctionId, functionId)
                .eq(DeviceData::getDeviceName, deviceName)
                .between(DeviceData::getAlarmTime, startTime, endTime)
                .page(Page.of(deviceDataPageReqDto.getPageNum(), deviceDataPageReqDto.getPageSize()));
        //2.返回TableDataInfo
        return TableDataInfo.getDataTable(page.getRecords(), page.getTotal());
    }
}
